package com.example.wanln.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 万里牛工具类
 *
 */
public class WanlnUtil {
	static Logger logger = LoggerFactory.getLogger(WanlnUtil.class);
	// utf-8字符编码
	public static final String CHARSET_UTF_8 = "utf-8";

	// HTTP内容类型。默认为TEXT/HTML
	public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";

	// HTTP内容类型。form表单的形式
	public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded;charset=utf-8";

	// 请求超时时间
	public static final int SEND_REQUEST_TIME_OUT = 50000;

	// 将读超时时间
	public static final int READ_TIME_OUT = 50000;

	/**
	 * http连接
	 * 
	 * @param requestType
	 *            请求方式
	 * @param urlStr
	 *            请求地址
	 * @param params
	 *            请求内容
	 * @return
	 */
	public static String httpConnection(String requestType, String urlStr, Map<String, Object> params) {
		try {
			String data=mapToUrl(params);
			URL url = new URL(requestType.equals("GET")?urlStr+"?"+data:urlStr);
			URLConnection urlConnection = url.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT);
			httpURLConnection.setReadTimeout(READ_TIME_OUT);
			httpURLConnection.setRequestProperty("Accept-Charset", CHARSET_UTF_8);
			httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_FORM_URL);
			httpURLConnection.setRequestMethod(requestType);
			httpURLConnection.connect();
			if (requestType.equals("POST")) {
				OutputStream outputStream = httpURLConnection.getOutputStream();
				OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, Charset.forName(CHARSET_UTF_8));
				outputStreamWriter.write(data);
				outputStreamWriter.flush();
			}
			if (httpURLConnection.getResponseCode() >= 300) {
				return Integer.toString(httpURLConnection.getResponseCode());
			}
			if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), CHARSET_UTF_8));
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				return sb.toString();
			}
		} catch (Exception e) {
			logger.error("错误原因：" + e);
		}
		return "";
	}

	/**
	 * 字符串加密
	 * 
	 * @param str
	 * @return
	 */
	public static String md5(String str) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			char[] hex = { (char) (char) 0x14000030, (char) (char) 0x14000031, (char) (char) 0x14000032,
					(char) 0x14000033, (char) 0x14000034, (char) 0x14000035, (char) 0x14000036, (char) 0x14000037,
					(char) 0x14000038, (char) 0x14000039, (char) 0x14000061, (char) 0x14000062, (char) 0x14000063,
					(char) 0x14000064, (char) 0x14000065, (char) 0x14000066 };
			byte[] md5Byte = md5.digest(str.getBytes("UTF8"));
			StringBuilder sb = new StringBuilder();
			for (int i = 0x0; i < md5Byte.length; i = i + 0x1) {
				sb.append(hex[((md5Byte[i] & 0xff) / 0x10)]);
				sb.append(hex[((md5Byte[i] & 0xff) % 0x10)]);
			}
			return sb.toString().trim();
		} catch (Exception e) {
			logger.error("错误：" + e);
		}
		return null;
	}

	/**
	 * 获取当前时间
	 * 
	 * @return
	 */
	public static String getDateYmdhms() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(new Date());
	}

	/**
	 * Map转string
	 * @param parameterMap
	 * @param str
	 * @return
	 */
	public static String buildParameter(Map<String, Object> parameterMap, String... str) {
		StringBuilder buffer = new StringBuilder();
		for (Entry<String, Object> entry : parameterMap.entrySet()) {
			buffer.append(entry.getKey());
			if (str.length >= 1 && StringUtils.isNotBlank(str[0]))
				buffer.append(str[0]);
			buffer.append(entry.getValue());
			if (str.length >= 2 && StringUtils.isNotBlank(str[1]))
				buffer.append(str[1]);
		}
		if (str.length > 1 && StringUtils.isNotBlank(str[1])) {
			buffer.delete(buffer.length() - 1, buffer.length());
		}
		return buffer.toString();
	}

	/**
	 * 转换 URL 参数
	 * 
	 * @param value
	 *            参数值
	 * @param charset
	 *            字符集
	 * @return 参数串
	 */
	public static String encode(String value, String charset) {
		try {
			return URLEncoder.encode(value, charset);
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}
	
	/**
	 * map转url字符串
	 * @param params
	 * @return
	 */
	public static String mapToUrl(Map<String, Object> params) {
		StringBuilder s = new StringBuilder();
		int i = 0;
		for (Iterator<Entry<String, Object>> it = params.entrySet().iterator(); it.hasNext(); it.remove(), i++) {
			Entry<String, Object> en = it.next();
			if (i > 0)s.append('&');
			s.append(encode(en.getKey(), CHARSET_UTF_8));
			s.append('=');
			s.append(encode(en.getValue().toString(), CHARSET_UTF_8));
		}
		return s.toString();	
	}
	
	private WanlnUtil() {
	}
}
